import { useState } from 'react'
import reactDom from 'react-dom'

let prevDepsAry = []
let prevIndex = 0

function useEffect(callback, depsAry) {
  if (Object.prototype.toString.call(callback) !== '[object Function]') throw Error('callback is not a function')

  if (typeof depsAry === 'undefined') {
    callback()
  } else {
    if (Object.prototype.toString.call(depsAry) !== '[object Array]') throw new Error('depsAry is not a Array')
    let hasChange = prevDepsAry[prevIndex] ? depsAry.every((dep, index) => dep === prevDepsAry[index]) === false : true
    console.log(prevIndex)
    if (hasChange) {
      callback()
    }
    prevDepsAry[prevIndex] = depsAry
    prevIndex++
  }
}

function render() {
  prevIndex = 0
  console.log(111)
  reactDom.render(<App></App>, document.getElementById('root'))
}

function App() {
  function getData() {
    return Promise.resolve('hello')
  }

  const [count, setCount] = useState(0)

  /**
   * 在 useEffect 中使用异步
   * 
   * 在 useEffect 中 返回值只能是一个普通函数
   * 所以直接使用async是不行的
   */
  useEffect(() => {
    (async () => {
      const result = await getData()
      console.log(result)
    })()
  }, [])

  function onScroll() {
    console.log('scroll')
  }
  useEffect(() => {
    // window.addEventListener('scroll', onScroll)
    // let timer = setInterval(() => {
    //   setCount(count => count + 1)
    // }, 1000)
    // return () => {
    //   clearInterval(timer)
    //   window.removeEventListener('scroll', onScroll)
    // }
    console.log('word')
  }, [])
  return (
    <div>
      <div>{count}</div>
      <button onClick={() => reactDom.unmountComponentAtNode(document.getElementById('root'))}>
        卸载
      </button>
      <button onClick={() => setCount(count + 1)}>count +</button>
    </div>
  )
}

export default App
